package com.liu.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.liu.fastjson.User;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author LIU
 * @version 1.0
 * @description TODO
 * @date 2024/4/23 10:47
 */
public class FastJsonTest {
    /**
     * 测试序列化，把Bean转Json
     *    默认不包含null值，输入null值SerializerFeature.WriteMapNullValue
     *    时间戳格式化
     *    指定属性和key映射关系
     *    不参与序列化
     */
    @Test
    public void test(){
        User user = new User();
        user.setName("小明");
        user.setId(1L);
//        user.setAddr("成都");
        user.setRegisterDate(new Date());
        user.setBirthDay(LocalDateTime.now());

        // SerializerFeature.WriteMapNullValue 输出null值 address:null
        String str = JSONObject.toJSONString(user,SerializerFeature.WriteMapNullValue);
        System.out.println(str);
    }

    /**
     *  TEST 字段大小写忽略
     *  test=222233
     */
    @Test
    public void parseObject(){
        String str ="{\"address\":null,\"birthDay\":\"2024-05-28 17:44:18\",\"id\":1,\"name\":\"小明\",\"TEST\":\"222233\"}";
        User user = JSONObject.parseObject(str, User.class);
        System.out.println(user);
    }
    /**
     *  TEST 字段大小写忽略
     *  test=222233
     */
    @Test
    public void parse() throws IOException {
        Path path = Paths.get("D:\\IDEA\\workspace\\basics\\java-base\\data\\fruit.json");

        System.out.println(path);
        String str = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        JSONObject object = JSONObject.parseObject(str);

        for (Map.Entry<String, Object> entry : object.entrySet()) {
            Object value = entry.getValue();
            JSONArray objects = JSON.parseArray(value.toString());
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = objects.getJSONObject(i);
                System.out.println(jsonObject.getString("title"));
                String imageUrl = jsonObject.getString("imageUrl");
                String sellPoint = jsonObject.getString("sellPoint");
                String categoryId = "1";
                String detailMobileHtml = "<p>"+ sellPoint +"</p>";
            }

        }
    }
}
